package com.example.multithread;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Description 计数器demo
 * @ClassName CountDownLatchTest1
 * @Author Administrator
 * @Date 2020/5/7 20:20
 * @Version 1.0
 */
public class CountDownLatchTest1 {
    public static void main(String[] args) {
        ExecutorService pool = Executors.newCachedThreadPool();
        CountDownLatch cdl = new CountDownLatch(100);
        for (int i = 0; i < 100; i++) {
            CountRunnable runnable = new CountRunnable(cdl);
            pool.execute(runnable);
        }
        pool.shutdown();
        System.out.println("---------------");
    }

    static class CountRunnable implements Runnable {
        private CountDownLatch countDownLatch;
        public CountRunnable(CountDownLatch countDownLatch) {
            this.countDownLatch = countDownLatch;
        }
        @Override
        public void run() {
            try {
                synchronized (countDownLatch) {
                    /*** 每次减少一个容量*/
                    countDownLatch.countDown();
                    System.out.println(Thread.currentThread().getName() + ", thread counts = " + (countDownLatch.getCount()));
                }
                countDownLatch.await();
                System.out.println(Thread.currentThread().getName() + ",concurrency counts = " + (100 - countDownLatch.getCount()));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

